include("core/utility/chatcommands.lua");

local plugin_meta = {};
plugin_meta.__index = rptr_meta;
plugin_meta.__tostring = function( self ) return self:GetPluginName(); end
plugin_meta.__tonumber = function( self ) return self:GetPluginID(); end
plugin_meta.__call = function( self ) self:OnPluginCalled(); end

local i = 0;
local PluginObjects = {};
function RegisterRaptorPlugin(name, command, privileges, description)
	i = i + 1;

	local plugin = {};
	setmetatable(plugin, plugin_meta);

	plugin.name = tostring( name );
	plugin.id 	= i;

	plugin.command  = command;
	plugin.minlevel = privileges;

	plugin.description = description;

	PluginObjects[ plugin.name ] = plugin;

	return plugin;
end

function GetRaptorPlugin( name )
	return PluginObjects[ tostring( name ) ];
end

function plugin_meta:GetPluginName()
	return self.name;
end

function plugin_meta:GetPluginID()
	return self.id;
end

local _rptrCall = hook.Call;
function hook.Call(name, gm, ...)
	if( table.Count( PluginObjects ) < 1 ) then return _rptrCall(name, gm, ...); end

	for _, module in pairs( PluginObjects ) do
		if( module[ name ] ) then
			local ret = { pcall(module[ name ], module, ...) };

			if( !ret[1] ) then
				module[ name ] = nil;
				ErrorNoHalt("Plugin hook failed! Plugin: "..module.name);
			else
				if( ret[2] ) then
					return unpack(ret, 2);
				end
			end
		end
	end

	return _rptrCall(name, gm, ...);
end